<template>
    <div class="tab-content">
        <!-- 操作按钮 -->
        <div class="operation-bar">
            <el-button type="primary" @click="openAddDialog">添加车辆状态</el-button>
        </div>
        
        <!-- 车辆状态表格 -->
        <el-table :data="tableData" border style="width: 100%" class="data-table">
            <el-table-column prop="plateNumber" label="车牌号" width="150" />
            <el-table-column prop="batteryLevel" label="电量" width="120">
                <template #default="scope">
                    {{ scope.row.batteryLevel }}%
                </template>
            </el-table-column>
            <el-table-column prop="range" label="续航里程" width="120">
                <template #default="scope">
                    {{ scope.row.range }}km
                </template>
            </el-table-column>
            <el-table-column prop="healthValue" label="健康值" width="120">
                <template #default="scope">
                    {{ scope.row.healthValue }}%
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button size="small" @click="editRow(scope.row, scope.$index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteRow(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 添加/编辑弹框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="dialogTitle" 
            width="500px"
            @close="resetForm"
        >
            <el-form 
                ref="formRef" 
                :model="formData" 
                :rules="formRules" 
                label-width="120px"
            >
                <el-form-item label="车牌号" prop="plateNumber">
                    <el-input v-model="formData.plateNumber" placeholder="请输入车牌号" />
                </el-form-item>
                <el-form-item label="电量" prop="batteryLevel">
                    <el-input-number 
                        v-model="formData.batteryLevel" 
                        :min="0" 
                        :max="100"
                        placeholder="请输入电量"
                        style="width: 90%"
                    />
                    <span style="margin-left: 8px; color: #999;">%</span>
                </el-form-item>
                <el-form-item label="续航里程" prop="range">
                    <el-input-number 
                        v-model="formData.range" 
                        :min="0" 
                        placeholder="请输入续航里程"
                        style="width: 90%"
                    />
                    <span style="margin-left: 8px; color: #999;">km</span>
                </el-form-item>
                <el-form-item label="健康值" prop="healthValue">
                    <el-input-number 
                        v-model="formData.healthValue" 
                        :min="0" 
                        :max="100"
                        placeholder="请输入健康值"
                        style="width: 90%"
                    />
                    <span style="margin-left: 8px; color: #999;">%</span>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updateDataClassify } from '@/api/port'

// 表格数据
const tableData = ref<Array<{
    plateNumber: string
    batteryLevel: number
    range: number
    healthValue: number
}>>([])

// 弹框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加车辆状态')
const isEdit = ref(false)
const editIndex = ref(-1)

// 表单数据
const formData = reactive({
    plateNumber: '',
    batteryLevel: 0,
    range: 0,
    healthValue: 0
})

// 表单验证规则
const formRules: FormRules = {
    plateNumber: [
        { required: true, message: '请输入车牌号', trigger: 'blur' },
        { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '请输入正确的车牌号格式', trigger: 'blur' }
    ],
    batteryLevel: [
        { required: true, message: '请输入电量', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '电量范围为0-100%', trigger: 'blur' }
    ],
    range: [
        { required: true, message: '请输入续航里程', trigger: 'blur' },
        { type: 'number', min: 0, message: '续航里程不能小于0', trigger: 'blur' }
    ],
    healthValue: [
        { required: true, message: '请输入健康值', trigger: 'blur' },
        { type: 'number', min: 0, max: 100, message: '健康值范围为0-100%', trigger: 'blur' }
    ]
}

const formRef = ref<FormInstance>()

// 打开添加弹框
const openAddDialog = () => {
    dialogTitle.value = '添加车辆状态'
    isEdit.value = false
    dialogVisible.value = true
    resetForm()
}

// 编辑行数据
const editRow = (row: any, index: number) => {
    dialogTitle.value = '编辑车辆状态'
    isEdit.value = true
    editIndex.value = index
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除行数据
const deleteRow = (index: number) => {
    ElMessageBox.confirm(
        '确定要删除这条车辆状态数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        tableData.value.splice(index, 1)
        ElMessage.success('删除成功')
        updateData()
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        plateNumber: '',
        batteryLevel: 0,
        range: 0,
        healthValue: 0
    })
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        
        if (isEdit.value) {
            // 编辑模式
            Object.assign(tableData.value[editIndex.value], formData)
            ElMessage.success('编辑成功')
        } else {
            // 添加模式
            tableData.value.push({ ...formData })
            ElMessage.success('添加成功')
        }
        await updateData()
        dialogVisible.value = false
        resetForm()
    } catch (error) {
        ElMessage.warning('请填写完整的表单信息')
    }
}

const updateData = async () => {
    // 调用保存接口
    await updateDataClassify({
        id: 5,
        key: 'module6',
        value: tableData.value
    })
    console.log('保存车辆状态数据配置:', tableData.value)
}

// 初始化函数
const init = (module: any) => {
    // 可以在这里重置表格数据或从API获取数据
    console.log('Module6 初始化',toRaw(module))
    if(module){
        tableData.value = module
    }
}

// 暴露方法给父组件
defineExpose({
    init
})
</script>
<style scoped>
.tab-content {
    padding: 20px;
}

.operation-bar {
    margin-bottom: 20px;
}

.data-table {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>